<template>
  <div class="app-container">
    <el-tabs v-model="queryParams.orderStatus" type="card" @tab-click="onOrderStatusChange">
      <el-tab-pane name="-1">
        <span slot="label"><i class="el-icon-s-order" /> 全部订单</span>
      </el-tab-pane>
      <el-tab-pane name="0">
        <span slot="label"><i class="el-icon-bank-card" /> 未支付</span>
      </el-tab-pane>
      <el-tab-pane name="1">
        <span slot="label"><i class="el-icon-refrigerator" /> 未发货</span>
      </el-tab-pane>
      <el-tab-pane name="2">
        <span slot="label"><i class="el-icon-truck" /> 待收货</span>
      </el-tab-pane>
      <el-tab-pane name="3">
        <span slot="label"><i class="el-icon-document" /> 待评价</span>
      </el-tab-pane>
      <el-tab-pane name="4">
        <span slot="label"><i class="el-icon-circle-check" /> 交易完成</span>
      </el-tab-pane>
    </el-tabs>
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item prop="value">
        <el-input v-model="queryParams.value" clearable placeholder="输入搜索内容" @keyup.enter.native="toQuery" />
      </el-form-item>
      <el-form-item prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="类型">
          <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="orderType">
        <el-select v-model="queryParams.orderType" clearable placeholder="订单类型">
          <el-option v-for="item in orderTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="daterange"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          range-separator="至"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-printer"
          size="mini"
          :disabled="multiple"
          @click="handlePrint"
        >批量打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleExport">
          <el-button
            v-hasPermi="['order:storeOrder:export']"
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
          >导出</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="0">导出全部</el-dropdown-item>
            <el-dropdown-item command="1" :disabled="multiple">导出选中</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-col class="order-overview" :span="12">
        <span>订单数 : <span>{{ overview.orderNum }}</span></span>
        <span>商品数 : <span>{{ overview.storeNum }}</span></span>
        <span>订单金额 : <span>{{ overview.orderPrice }}</span></span>
        <span>客户数 : <span>{{ overview.userNum }}</span></span>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="storeOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" align="center">
        <template slot-scope="{$index}">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="orderId" width="200" label="订单号" header-align="center">
        <template slot-scope="{row}">
          <div>{{ row.orderId }}</div>
          <div>{{ row.pinkName }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="用户昵称" header-align="center">
        <template slot-scope="{row}">
          <span>{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="cartInfoList" width="400" label="商品信息" header-align="center">
        <template slot-scope="{row}">
          <div v-for="(item, index) in row.cartInfoList" :key="index">
            <span v-if="item.cartInfoMap.productInfo.attrInfo">
              <img style="width: 30px;height: 30px;margin:0;" :src="item.cartInfoMap.productInfo.attrInfo.image">
            </span>
            <span v-else>
              <img style="width: 30px;height: 30px;margin:0;" :src="item.cartInfoMap.productInfo.image">
            </span>
            <span>
              {{ item.cartInfoMap.productInfo.storeName }}
              <span v-if="item.cartInfoMap.productInfo.attrInfo">&nbsp;{{ item.cartInfoMap.productInfo.attrInfo.sku
              }}</span>
            </span>
            <span> | ￥{{ multiply(item.cartInfoMap.truePrice, item.cartInfoMap.cartNum) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="payPrice" label="实际支付" header-align="center" align="right" />
      <el-table-column prop="payIntegral" label="消费积分" align="center" />
      <el-table-column prop="payTypeName" label="支付状态" align="center" />
      <el-table-column prop="statusName" label="订单状态" header-align="center">
        <template slot-scope="{row}">
          <span v-html="row.statusName" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" width="160" label="创建时间" align="center" :formatter="formatDate" />
      <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" width="200">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" style="margin-right: 5px;" @click="viewDetail(row.id)">
            订单详情
          </el-button>
          <el-dropdown size="mini" split-button type="success" trigger="click" @command="c => onCommand(c, row)">
            操作
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="remark">
                订单备注
              </el-dropdown-item>
              <el-dropdown-item v-if="row._status == 2" command="deliver">
                去发货
              </el-dropdown-item>
              <el-dropdown-item v-if="row._status == 4" command="express">
                修改快递
              </el-dropdown-item>
              <el-dropdown-item v-if="row._status == 3" command="refund">
                立刻退款
              </el-dropdown-item>
              <el-dropdown-item v-if="row._status == 1" v-hasPermi="['order:storeOrder:edit']" command="update">
                修改
              </el-dropdown-item>
              <el-dropdown-item v-if="row._status == 1" v-hasPermi="['order:storeOrder:remove']" command="delete">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form v-if="dialog.currentMode === 'update'" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" disabled />
        </el-form-item>
        <el-form-item label="原始邮费" prop="totalPostage">
          <el-input v-model="form.totalPostage" disabled />
        </el-form-item>
        <el-form-item label="实际支付" prop="payPrice">
          <el-input v-model="form.payPrice" />
        </el-form-item>
      </el-form>
      <el-form
        v-else-if="dialog.currentMode === 'deliver' || dialog.currentMode === 'express'"
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="快递公司" prop="deliveryName">
          <el-select v-model="form.deliveryName" filterable placeholder="请选择">
            <el-option v-for="item in express" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="deliveryId">
          <el-input v-model="form.deliveryId" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="dialog.currentMode === 'refund'" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" disabled />
        </el-form-item>
        <el-form-item label="退款金额" prop="payPrice">
          <el-input v-model="form.payPrice" />
        </el-form-item>
      </el-form>
      <el-form v-else-if="dialog.currentMode === 'remark'" ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" disabled />
        </el-form-item>
        <el-form-item label="订单备注" prop="remark">
          <el-input v-model="form.remark" rows="5" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <print-dialog :visible.sync="printDialog.open" :list="printDialog.list" />
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { multiply } from '@/utils/math'
import { listStoreOrder, delStoreOrder, addStoreOrder, updateStoreOrder } from '@/api/order/storeOrder'
import PrintDialog from './PrintDialog.vue'

export default {
  name: 'StoreOrder',
  components: {
    PrintDialog
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 订单表格数据
      storeOrderList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: '-1',
        value: '',
        type: '',
        orderType: '0',
        createTime: []
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      types: [
        { value: 'orderId', label: '订单号' },
        { value: 'realName', label: '用户姓名' },
        { value: 'userPhone', label: '用户电话' }
      ],
      orderTypes: [
        { value: '0', label: '所有订单' },
        { value: '1', label: '普通订单' },
        { value: '2', label: '拼团订单' },
        { value: '3', label: '秒杀订单' },
        { value: '4', label: '砍价订单' },
        { value: '5', label: '核销订单' },
        { value: '6', label: '积分订单' }
      ],
      printDialog: {
        open: false,
        list: []
      },
      overview: {},
      dialog: {
        modes: {
          remark: {
            title: '修改订单'
          },
          deliver: {
            title: '去发货'
          },
          express: {
            title: '修改快递'
          },
          refund: {
            title: '退款'
          },
          update: {
            title: '修改订单'
          }
        },
        currentMode: ''
      },
      express: []
    }
  },
  computed: {
    title() {
      const { modes, currentMode } = this.dialog
      return modes[currentMode]?.title || ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    multiply,
    /** 查询订单列表 */
    getList() {
      this.loading = true
      this.storeOrderList = []
      listStoreOrder(this.queryParams).then(response => {
        this.storeOrderList = response.rows
        this.total = response.total
      }).finally(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset(row) {
      this.form = JSON.parse(JSON.stringify(row)) || {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateStoreOrder(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addStoreOrder(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true
        return delStoreOrder(ids)
      }).then(() => {
        this.loading = false
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      }).finally(() => {
        this.loading = false
      })
    },
    /** 导出按钮操作 */
    handleExport(command) {
      /** page: 0
size: 10000
sort: id,desc
orderStatus: -9
orderType: 0
createTime:
listContent: ["1627920685013663744","1627930721404321792","1627864121783353344"] */
      if (command === '0') {
        this.download('order/storeOrder/export', {}, `storeOrder_${new Date().getTime()}.xlsx`)
      } else if (command === '1') {
        const listContent = this.ids.map(item => item.id)
        this.download('order/storeOrder/export', { listContent: JSON.stringify(listContent) }, `storeOrder_${new Date().getTime()}.xlsx`)
      }
    },
    onOrderStatusChange() {
      this.handleQuery()
    },
    handlePrint() {
      this.printDialog.list = this.ids
      this.printDialog.open = true
    },
    formatDate(row) {
      return dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    onCommand(c, row) {
      if (c === 'delete') {
        this.handleDelete(row)
      } else {
        this.dialog.currentMode = c
        this.reset(row)
        this.open = true
      }
    },
    viewDetail(id) {}
  }
}
</script>
<style lang="scss" scoped>
.order-overview {
  float: right;
  text-align: right;
}
</style>
